package com.yiqi.zhiyuan.feature.certification.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.EventEntity;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.rxbus2.RxBus;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.widget.dialog.ActionSheetDialog;
import com.suozhang.framework.widget.dialog.OnOperItemClickL;
import com.yiqi.zhiyuan.R;
import com.yiqi.zhiyuan.entity.bo.UploadCertificatesInfo;
import com.yiqi.zhiyuan.entity.dto.DiverCertificationDTO;
import com.yiqi.zhiyuan.entity.vo.ReviewVo;
import com.yiqi.zhiyuan.feature.certification.contract.UploadContract;
import com.yiqi.zhiyuan.feature.certification.dependencies.upload.DaggerUploadComponent;
import com.yiqi.zhiyuan.feature.certification.dependencies.upload.UploadPresenterModule;
import com.yiqi.zhiyuan.feature.certification.view.adapter.UploadCertificatesAdapter;
import com.yiqi.zhiyuan.feature.main.view.MainActivity;
import com.yiqi.zhiyuan.framework.DataServer;
import com.yiqi.zhiyuan.framework.ZYConstants;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @ProjectName: ZhiYuan
 * @Package: com.yiqi.zhiyuan.feature.login.view
 * @ClassName: UploadCertificatesActivity
 * @Description: 上传证件
 * @Author:
 * @CreateDate: 2019/3/12 10:10
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/3/12 10:10
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class UploadCertificatesActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener,
        OnOperItemClickL, Toolbar.OnMenuItemClickListener, UploadContract.View, BaseQuickAdapter.OnItemChildClickListener {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.rv_upload_list)
    RecyclerView mRvUploadList;
    @BindView(R.id.tab_certificate_register)
    TextView mTabCertificateRegister;
    @BindView(R.id.tab_certificate_info)
    TextView mTabCertificateInfo;
    @BindView(R.id.tab_certificate_image)
    TextView mTabCertificateImage;
    private List<LocalMedia> selectList;
    private int mPosition;
    private boolean isFirst = false;

    UploadCertificatesAdapter mAdapter;
    List<UploadCertificatesInfo> mCertificatesInfos;
    ActionSheetDialog dialog;

    private DiverCertificationDTO mCertificationDTO;

    @Inject
    UploadContract.Presenter mPresenter;

    ReviewVo mReviewVo;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_upload_certificates;
    }

    @Override
    protected void initInjector() {
        DaggerUploadComponent.builder().uploadPresenterModule(new UploadPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {

        RxBus.getDefault().register(this);

        initToolBar(mToolbar, "上传证件", true, true);
        initAdapter();


        final String[] stringItems = {"拍照", "从手机相册选择"};
        dialog = new ActionSheetDialog(this, stringItems, null);
        dialog.isTitleShow(false);
        dialog.setOnOperItemClickL(this);
    }

    private void initAdapter() {
        if (mCertificatesInfos == null) {
            mCertificatesInfos = DataServer.getUploadType();
        }
        mRvUploadList.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new UploadCertificatesAdapter();
        mAdapter.bindToRecyclerView(mRvUploadList);
        mAdapter.setNewData(mCertificatesInfos);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void initData() {

        isFirst = this.getIntent().getBooleanExtra("is_first", false);
        mReviewVo = (ReviewVo) this.getIntent().getSerializableExtra("auth_images");
        mCertificationDTO = (DiverCertificationDTO) this.getIntent().getSerializableExtra("certificate_info");
        setImages(mReviewVo);
        initTabView(isFirst);
    }

    /**
     * 设置已上传证件照片
     */
    private void setImages(ReviewVo mReviewVo) {
        if (mReviewVo == null) return;
        List<UploadCertificatesInfo> uploadCertificatesInfos = new ArrayList<>();
        for (int i = 0; i < mCertificatesInfos.size(); i++) {
            UploadCertificatesInfo info = mCertificatesInfos.get(i);
            if (info.getName().equals("idCardPositive")) {
                info.setImgUrl(mReviewVo.getIdCardPositive());
            }
            if (info.getName().equals("driverPositive")) {
                info.setImgUrl(mReviewVo.getDriverPositive());
            }
            if (info.getName().equals("travelPositive")) {
                info.setImgUrl(mReviewVo.getTravelPositive());
            }
            if (info.getName().equals("bankCardPositive")) {
                info.setImgUrl(mReviewVo.getBankCardPositive());
            }
            if (info.getName().equals("operationPositive")) {
                info.setImgUrl(mReviewVo.getOperationPositive());
            }
            if (info.getName().equals("netCarPositive")) {
                info.setImgUrl(mReviewVo.getNetCarPositive());
            }
            if (info.getName().equals("carPersonPositive")) {
                info.setImgUrl(mReviewVo.getCarPersonPositive());
            }
            uploadCertificatesInfos.add(info);
        }
        mAdapter.setNewData(uploadCertificatesInfos);
    }

    /**
     * 初始化头部选择按钮
     */
    private void initTabView(boolean isCer) {
        if (isCer) {
            mToolbar.inflateMenu(R.menu.menu_skip);
        } else {
            mTabCertificateRegister.setText("填写资料");
            mTabCertificateInfo.setVisibility(View.GONE);
        }
    }


    @Override
    protected void initEvent() {
        mToolbar.setOnMenuItemClickListener(this);
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        mPosition = position;
        dialog.show();
    }

    @Override
    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0:
                PictureSelector.create(this)
                        .openCamera(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style)
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                        .previewImage(true)// 是否可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .enableCrop(true)// 是否裁剪
                        .compress(true)// 是否压缩
                        .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                        .isGif(false)// 是否显示gif图片
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case 1:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style)
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                        .previewImage(true)// 是否可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .isCamera(false)
                        .enableCrop(true)// 是否裁剪
                        .compress(true)// 是否压缩
//                        .cropCompressQuality(2)
                        .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                        .isGif(false)// 是否显示gif图片
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .scaleEnabled(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;

        }

        if (dialog != null) {
            dialog.dismiss();
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < selectList.size(); i++) {
                        UploadCertificatesInfo info = mCertificatesInfos.get(mPosition);
                        info.setImgUrl(selectList.get(i).getCompressPath());
                        mCertificatesInfos.set(mPosition, info);
                        if (mAdapter != null) {
                            mAdapter.setData(mPosition, info);
                        }
                    }

                    break;
            }
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        startActivity(new Intent(this, MainActivity.class));
        finish();
        return false;
    }


    @OnClick(R.id.tv_user_upload)
    public void onViewClicked() {
        mPresenter.uploadCertificate(mCertificatesInfos, mCertificationDTO);
    }

    @Override
    public void showUploadCertificateSuccess() {
        RxBus.getDefault().post(new EventEntity(ZYConstants.CertificateSuccess, 0));
        if (isFirst) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        } else {
            finish();
        }
    }

    @Override
    public void showUploadCertificateError(String errorMsg) {
        showMsg(errorMsg);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        UploadCertificatesInfo uploadCertificatesInfo = mAdapter.getItem(position);
        uploadCertificatesInfo.setImgUrl(null);
        mCertificatesInfos.set(position, uploadCertificatesInfo);
        mAdapter.setData(position, uploadCertificatesInfo);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //保存销毁之前的数据
        outState.putSerializable("info", (Serializable) mCertificatesInfos);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mCertificatesInfos = (List<UploadCertificatesInfo>) savedInstanceState.getSerializable("info");
        }
    }

}
